package com.feemanage.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.common.api.ApprovalApi;
import com.common.core.domain.entity.SysUser;
import com.common.core.page.PageDomain;
import com.common.exception.ServiceException;
import com.common.utils.CurrentRoleUtils;
import com.common.utils.SecurityUtils;
import com.common.utils.bean.BizProcessMessages;
import com.common.utils.sql.SqlUtil;
import com.feemanage.common.SearchUtils;
import com.feemanage.domain.*;
import com.feemanage.domain.bo.BizCwIncomeClaimAllBo;
import com.feemanage.domain.bo.BizCwIncomeClaimBo;
import com.feemanage.domain.vo.*;
import com.feemanage.mapper.*;
import com.feemanage.service.IBizClaimFeeCardBudgetService;
import com.feemanage.service.IBizClaimManageFeeService;
import com.feemanage.service.ISysSnruleService;
import com.feemanage.service.IcWIncomeClaimService;
import com.flowable.domain.vo.task.BpmTaskApproveReqVO;
import com.flowable.service.IFlowTaskService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Service("biz_cw_income_claim")
public class cWIncomeClaimServiceImpl implements IcWIncomeClaimService {

    @Autowired
    private cWIncomeClaimMapper baseMapper;

    @Autowired
    private cWIncomeMapper incomeMapper;

    @Autowired
    private bizClaimManageMapper manageMapper;

    @Autowired
    private bizProjectFeeCardMapper feeCardMapper;

    @Autowired
    private bizClaimFeeCardBudgetMapper budgetMapper;

    @Autowired
    private bizClaimProjectIncomeMapper claimProjectIncomeMapper;

    @Autowired
    private bizProjectIncomeMapper proincomeMapper;

    @Autowired
    private bizProjectFeeCardBudgetMapper probudgetMapper;

    @Autowired
    private bizManageFeeMapper promanageMapper;

    @Autowired
    private IBizClaimManageFeeService manageFeeService;

    @Autowired
    private IBizClaimFeeCardBudgetService budgetService;

    @Autowired
    private ISysSnruleService sysSnruleService;

    @Autowired
    private ApprovalApi approvalApi; //发起流程

    @Autowired
    private IFlowTaskService flowTaskService;//流程引擎

    private final static String claimtype="cwIncomeClaim"; //认领类型
    private final static String project_Class_zX="zXProject"; // 纵向项目

    private final static String project_Class_yf="yfContract"; // 横向项目

    private final static String budgetSplitModde_lx = "liuxiaoBudgetSplit" ;//额度拆分方式--拆分总留校额度

    private final static String budgetSplitModde = "chargerConfirm" ;//额度拆分方式--默认负责人拆分

    private  final static  String modelName="经费认领";

    /**
     * 查询银行到款列表
     * @param pageDomain
     * @param claim
     * @return
     */
    @Override
    public IPage<BizCwIncomeClaimVo> selectList(PageDomain pageDomain, BizCwIncomeClaimBo claim) {
        Page<BizCwIncomeClaim> page = new Page<>(pageDomain.getPageNum(), pageDomain.getPageSize());
        QueryWrapper<BizCwIncomeClaim> wrapper = getQuery(claim);
        String orderByColumn = SqlUtil.escapeOrderBySql(pageDomain.getOrderByColumn());
        boolean isASC = SqlUtil.escapeOrderBySql(pageDomain.getIsAsc()).equalsIgnoreCase("asc");
        if (!StringUtils.isEmpty(orderByColumn))
        {
            wrapper.orderBy(true,isASC,orderByColumn);
        }
        IPage<BizCwIncomeClaimVo> list = baseMapper.selectClaimList(page,wrapper);
        // 获取流程任务列表,Map<instanceId, taskId>
        Map<String, String> instanceTaskMap = approvalApi.getInstanceTaskMap(modelName);
        for (BizCwIncomeClaimVo u : list.getRecords()) {
            // 判断是否是审核人，并设置taskId
            String processInstanceId = u.getProcessInstanceId();
            if (com.common.utils.StringUtils.isNotEmpty(processInstanceId) && instanceTaskMap.containsKey(processInstanceId)) {
                u.setTaskId(instanceTaskMap.get(processInstanceId));
                u.setIsAuditor(true);
            } else {
                u.setIsAuditor(false);
            }
        }
        return list;
    }

    /**
     * 统计表头
     * @param claim
     * @return
     */
    @Override
    public List<HashMap<String, Integer>> selectListTotal(BizCwIncomeClaimBo claim) {
        QueryWrapper<BizCwIncomeClaim> wrapper = getQuery(claim);
        return baseMapper.selectListTotal(wrapper);
    }


    /**
     * 导出
     * @param claim
     * @return
     */
    @Override
    public List<BizCwIncomeClaimVo> selectExportList(PageDomain pageDomain,BizCwIncomeClaimBo claim) {
        QueryWrapper<BizCwIncomeClaim> wrapper = getQuery(claim);
        String orderByColumn = SqlUtil.escapeOrderBySql(pageDomain.getOrderByColumn());
        boolean isASC = SqlUtil.escapeOrderBySql(pageDomain.getIsAsc()).equalsIgnoreCase("asc");
        if (!StringUtils.isEmpty(orderByColumn))
        {
            wrapper.orderBy(true,isASC,orderByColumn);
        }
        return baseMapper.selectClaimList(wrapper);
    }

    /**
     * 拼接条件
     * @param claim
     * @return
     */
    public  QueryWrapper<BizCwIncomeClaim> getQuery(BizCwIncomeClaimBo claim) {
        Map<String, Object> params = claim.getParams();
        QueryWrapper<BizCwIncomeClaim> wrapper = Wrappers.query();
        wrapper.eq(StringUtils.isNotBlank(claim.getId()),"c.id", claim.getId())
                .eq(StringUtils.isNotBlank(claim.getProjectId()),"p.id", claim.getProjectId())
                .eq(StringUtils.isNotBlank(claim.getCwIncomeId()), "c.cw_income_id", claim.getCwIncomeId())
                .eq(StringUtils.isNotBlank(claim.getChargerId()),"p.charger_code",claim.getChargerId())
                .eq(StringUtils.isNotBlank(claim.getCheckstatus()),"c.checkstatus",claim.getCheckstatus())
                .like(StringUtils.isNotBlank(claim.getCwDch()), "b.cw_dch", claim.getCwDch())
                .like(StringUtils.isNotBlank(claim.getProjectName()), "p.name", claim.getProjectName())
                .like(StringUtils.isNotBlank(claim.getChargerName()), "p.charger_name", claim.getChargerName())
                .between(ObjectUtil.isNotEmpty(params.get("beginTime")) && ObjectUtil.isNotEmpty(params.get("endTime")),
                        "c.claim_date", params.get("beginTime"), params.get("endTime"))
                .ge(ObjectUtil.isNotEmpty(params.get("beginTime")) && ObjectUtil.isEmpty(params.get("endTime")),"c.claim_date", params.get("beginTime"))
                .le(ObjectUtil.isEmpty(params.get("beginTime")) && ObjectUtil.isNotEmpty(params.get("endTime")),"c.claim_date", params.get("endTime"))
                .between(ObjectUtil.isNotEmpty(params.get("maxfee"))  && ObjectUtil.isNotEmpty(params.get("minfee")),
                        "c.claim_fee", SearchUtils.processAmount(params.get("minfee")), SearchUtils.processAmount(params.get("maxfee")))
                .ge(ObjectUtil.isNotEmpty(params.get("minfee")) && ObjectUtil.isEmpty(params.get("maxfee")),"c.claim_fee", SearchUtils.processAmount(params.get("minfee")))
                .le(ObjectUtil.isNotEmpty(params.get("maxfee")) && ObjectUtil.isEmpty(params.get("minfee")),"c.claim_fee", SearchUtils.processAmount(params.get("maxfee")))
                .between(ObjectUtil.isNotEmpty(params.get("maxschool")) && ObjectUtil.isNotEmpty(params.get("minschool")),
                        "c.school_fee", SearchUtils.processAmount(params.get("minschool")), SearchUtils.processAmount(params.get("maxschool")))
                .ge(ObjectUtil.isNotEmpty(params.get("minschool")) && ObjectUtil.isEmpty(params.get("maxschool")),"c.school_fee", SearchUtils.processAmount(params.get("minschool")))
                .le(ObjectUtil.isNotEmpty(params.get("maxschool")) && ObjectUtil.isEmpty(params.get("minschool")),"c.school_fee", SearchUtils.processAmount(params.get("maxschool")))
                .between(ObjectUtil.isNotEmpty(params.get("maxoutfee")) && ObjectUtil.isNotEmpty(params.get("minoutfee")),
                        "c.outbound_fee", SearchUtils.processAmount(params.get("minfee")), SearchUtils.processAmount(params.get("maxoutfee")))
                .ge(ObjectUtil.isNotEmpty(params.get("minoutfee")) && ObjectUtil.isEmpty(params.get("maxoutfee")),"c.outbound_fee", SearchUtils.processAmount(params.get("minoutfee")))
                .le(ObjectUtil.isNotEmpty(params.get("maxoutfee")) && ObjectUtil.isEmpty(params.get("minoutfee")),"c.outbound_fee", SearchUtils.processAmount(params.get("maxoutfee")));
        if(StringUtils.isNotEmpty(claim.getProjectType())){
            List<String> list = Arrays.stream(claim.getProjectType().split(",")).collect(Collectors.toList());
            wrapper.in("p.project_type",list);
        }
        if(StringUtils.isNotEmpty(claim.getUnitId())){
            List<String> list = Arrays.stream(claim.getUnitId().split(",")).collect(Collectors.toList());
            wrapper.in("p.unit_id",list);
        }
        if(StringUtils.isNotEmpty(claim.getProjectClass())){
            List<String> list = Arrays.stream(claim.getProjectClass().split(",")).collect(Collectors.toList());
            wrapper.in("p.project_class",list);
        }
        if(StringUtils.isNotEmpty(claim.getStatus())){
            List<String> list = Arrays.stream(claim.getStatus().split(",")).collect(Collectors.toList());
            wrapper.in("c.checkstatus",list);
        }
        //当前用户的角色
        String currentRoleKey = CurrentRoleUtils.getCurrentRoleKey();
        SysUser loginUser = SecurityUtils.getLoginUser().getUser();
        if (("biz_kyry").equals(currentRoleKey)) {//科研人员
            wrapper.eq("p.charger_code",loginUser.getUserRealId());
        }
        if (("biz_kyms").equals(currentRoleKey)) {//科研秘书
            String units = loginUser.getUnitAdminScopeReal();
            if (StringUtils.isNotEmpty(units)) {
                List<String> unit = Arrays.stream(units.split(",")).collect(Collectors.toList());
                wrapper.in("p.unit_id",unit);
            }
        }
        return wrapper;
    }

    /**
     * 新增
     * @param claimAllBo
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public String addCwIncomeclaim(BizCwIncomeClaimAllBo claimAllBo) {
        SysUser loginUser = SecurityUtils.getLoginUser().getUser();
        Long count = incomeMapper.selectCount(new LambdaQueryWrapper<BizCwIncome>().eq(BizCwIncome::getId,claimAllBo.getClaimShow().getCwIncomeId()));
        if (count < 0) {
            throw new ServiceException("当前来款信息不存在");
        }

        BizCwIncomeClaim claim = new BizCwIncomeClaim();
        BeanUtils.copyProperties(claimAllBo.getClaimShow(),claim);
        claim.setClaimType(claimtype);
        if (ObjectUtil.isNotNull(loginUser)) {
            claim.setClaimerId(loginUser.getUserRealId());
            claim.setClaimerName(loginUser.getNickName());
        }
        claim.setClaimDate(LocalDateTime.now());
        claim.setFeeSchemeId(claimAllBo.getClaimFeeShow().getFeeSchemeId());//管理方案
        //暂存和保存并通过
        if (!claimAllBo.getClaimShow().getStatus().equals("1")){
            claim.setCheckstatus(claimAllBo.getClaimShow().getStatus());
            claim.setChecker(loginUser.getNickName());
            claim.setCheckdate(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            if(claimAllBo.getClaimShow().getStatus().equals("2")){
                claim.setProcessInstanceId("0");
            }
        }
        boolean flag = baseMapper.insert(claim)>0; //BIZ_CW_INCOME_CLAIM

        if(flag){
            claimAllBo.getClaimShow().setId(claim.getId());//反写claimid
            //BIZ_CLAIM_PROJECT_INCOME表
            insertIncomeProjectClaim(claimAllBo.getClaimFeeShow().getClaimIncomeFeeShow(), claim);

            boolean budegtflag = true;

            //留校总额度，去查一下有没有插入数据
            if(claimAllBo.getClaimShow().getBudgetSplitModde().equals(budgetSplitModde_lx)){
                QueryWrapper<BizClaimFeeCardBudget> queryWrapper = Wrappers.query();
                queryWrapper.eq("PROJECT_ID",claim.getProjectId());
                String cardnum = claimAllBo.getClaimFeeShow().getClaimIncomeFeeShow().get(0).getFeeCardNum();
                if(StringUtils.isEmpty(cardnum)){
                    queryWrapper.isNull("FEE_CARD_NUM");
                }else {
                    queryWrapper.eq("FEE_CARD_NUM",cardnum);
                }
                count = budgetMapper.selectCount(queryWrapper);

                if(count >0){
                    budegtflag = false;
                }
            }else{
                //横向项目，未确认额度拆分，不保存
                if (claimAllBo.getClaimFeeShow().getProjectClass().equals(project_Class_yf) && claimAllBo.getClaimShow().getBudgetSplitModde().equals(budgetSplitModde))
                {
                    budegtflag = false;
                }
            }

            //预算科目费用，BIZ_CLAIM_FEE_CARD_BUDGET
            if (budegtflag){
                List<BizClaimFeeCardBudget> budgetList = getBudgetList(claimAllBo);
                if (budgetList !=null && !budgetList.isEmpty()){
                    flag = budgetService.saveBatch(budgetList);
                }
            }

            //纵向项目有管理费 BIZ_CLAIM_MANAGE_FEE
            if(claimAllBo.getClaimFeeShow().getProjectClass().equals(project_Class_zX)){
                List<BizClaimManageFee> manageFeeList = getManageList(claimAllBo);
                if(manageFeeList!=null && !manageFeeList.isEmpty()){
                    flag = manageFeeService.saveBatch(manageFeeList);
                }
            }
        }

        String msg = flag ? null :"操作失败";
        if(StringUtils.isEmpty(msg)){
            //提交 1
            if(claimAllBo.getClaimShow().getStatus().equalsIgnoreCase("1")){
                String processInstanceId = approvalApi.businessEntryApproval(claim.getId(), modelName);
                msg = StringUtils.isEmpty(processInstanceId)? BizProcessMessages.SAVE_PARTIAL_SUCCESS:null;
            }
            //保存并通过 2
            if(claimAllBo.getClaimShow().getStatus().equalsIgnoreCase("2")){
                updateBusinessStatus("local",claim.getId(),"2",loginUser.getNickName());
            }
        }
        updateIncomeStatus(claimAllBo.getClaimShow().getCwIncomeId());//更新BIZ_CW_INCOME的FEESTATUS
        return msg;
    }

    public void updateIncomeStatus(String id){
        BizCwIncomeVo incomeVo = incomeMapper.selectListOne(new QueryWrapper<BizCwIncome>().eq("c.id",id));
        BizCwIncome income = new BizCwIncome();
        if(ObjectUtils.isNotEmpty(incomeVo)){
            int result = incomeVo.getFeeValue().compareTo(incomeVo.getNotClaimfee());
            if(incomeVo.getNotClaimfee().equals(incomeVo.getFeeValue())){ //未认领
                income.setFeeStatus("0");
            }
            else if(result > 0){ //认领中
                income.setFeeStatus("1");
            }else{
                income.setFeeStatus("2"); //认领完毕
            }
            incomeMapper.update(income, new UpdateWrapper<BizCwIncome>().eq("ID", id));//更新状态
        }
    }

    /**
     * 编辑
     * @param claimAllBo
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public String editCwIncomeclaim(BizCwIncomeClaimAllBo claimAllBo) {
        SysUser loginUser = SecurityUtils.getLoginUser().getUser();
        BizCwIncomeClaim claim = new BizCwIncomeClaim();
        BeanUtils.copyProperties(claimAllBo.getClaimShow(),claim);
        claim.setClaimDate(LocalDateTime.of(claimAllBo.getClaimShow().getClaimDate(), LocalTime.MIN));
        //按钮状态为-1暂存和保存2
        if (!claimAllBo.getClaimShow().getStatus().equals("1")){
            //数据状态不为审核中1时，才会更新状态（此时数据状态为-1暂存，3不通过，按钮为-1，2，数据状态为-1，2）
            if(!claimAllBo.getClaimShow().getCheckstatus().equalsIgnoreCase("1")){
                claim.setCheckstatus(claimAllBo.getClaimShow().getStatus());
                claim.setChecker(loginUser.getNickName());
                claim.setCheckdate(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                if(claimAllBo.getClaimShow().getStatus().equals("2")){
                    claim.setProcessInstanceId("0");
                }
            }
        }
        Boolean flag = baseMapper.updateById(claim) >0;
        if(flag){
            //先删除对应表的数据 BIZ_CLAIM_PROJECT_INCOME
            claimProjectIncomeMapper.delete(new QueryWrapper<BizClaimProjectIncome>().in("CW_INCOME_CLAIM_ID",claim.getId()));
            insertIncomeProjectClaim(claimAllBo.getClaimFeeShow().getClaimIncomeFeeShow(), claim);


            //BIZ_CLAIM_FEE_CARD_BUDGET
            //编辑时，按留校总额的拆分，不更新
            if (!claim.getBudgetSplitModde().equals(budgetSplitModde_lx)) {
                List<BizClaimFeeCardBudget> budgetList = getBudgetList(claimAllBo);
                budgetMapper.delete(new QueryWrapper<BizClaimFeeCardBudget>().in("CLAIM_ID",claim.getId()));
                if (budgetList!=null && !budgetList.isEmpty()){
                    flag = budgetService.saveBatch(budgetList);
                }
            }

            //纵向项目有管理费 BIZ_CLAIM_MANAGE_FEE
            if(claimAllBo.getClaimFeeShow().getProjectClass().equals(project_Class_zX)){
                List<BizClaimManageFee> manageFeeList = getManageList(claimAllBo);
                manageMapper.delete(new QueryWrapper<BizClaimManageFee>().in("CLAIM_ID",claim.getId()));
                if(flag && manageFeeList!=null && !manageFeeList.isEmpty()){
                    flag = manageFeeService.saveBatch(manageFeeList);
                }
            }
        }
        String msg = flag ? null :"操作失败";
        // 按钮状态为提交1:那么当前角色为科研人员，调用流程引擎
        if(claimAllBo.getClaimShow().getStatus().equalsIgnoreCase("1")){
            String returnProcessInstanceId = approvalApi.businessEntryApproval(claim.getId(), modelName);
            msg = StringUtils.isEmpty(returnProcessInstanceId)?BizProcessMessages.SAVE_PARTIAL_SUCCESS:null;
        }

        //按钮为保存并通过2:当前角色为科研秘书/科研管理员
        if(claimAllBo.getClaimShow().getStatus().equalsIgnoreCase("2")){
            //当数据状态为暂存和不通过时，直接更新数据状态，不走流程引擎
            if(claimAllBo.getClaimShow().getCheckstatus().equalsIgnoreCase("-1") || claimAllBo.getClaimShow().getCheckstatus().equalsIgnoreCase("3")){
                updateBusinessStatus("local",claim.getId(),"2",loginUser.getNickName());
            }else{
                //当为审核中时，前端角色判断了，此时应该为当前审核人，则走流程引擎，该流程节点通过
                BpmTaskApproveReqVO bta = new BpmTaskApproveReqVO();
                bta.setId(claimAllBo.getClaimShow().getTaskId());
                bta.setReason(SecurityUtils.getNickName() + "保存并通过");
                flowTaskService.approveTask(SecurityUtils.getUserId(), bta);
            }
        }
        updateIncomeStatus(claimAllBo.getClaimShow().getCwIncomeId());//更新BIZ_CW_INCOME的FEESTATUS
        return msg;
    }

    /**
     * 写入BIZ_CLAIM_PROJECT_INCOME表
     * @param incomeFeeList
     * @param claim
     */
    private void insertIncomeProjectClaim(List<ClaimIncomeFeeVo> incomeFeeList, BizCwIncomeClaim claim) {
        BizCwIncome income = new BizCwIncome();
        if(StringUtils.isNotEmpty(claim.getCwIncomeId())){
             income = incomeMapper.selectById(claim.getCwIncomeId());
        }
        for (ClaimIncomeFeeVo incomeFeeVo :incomeFeeList){
            BizClaimProjectIncome projectIncome = new BizClaimProjectIncome();
            BeanUtils.copyProperties(incomeFeeVo,projectIncome);
            projectIncome.setCwIncomeClaimId(claim.getId());
            projectIncome.setFeeSchemeId(claim.getFeeSchemeId());//管理方案id
            projectIncome.setIncomeType(claim.getIncomeType());//来款类型
            projectIncome.setCwIncomeId(claim.getCwIncomeId());
            projectIncome.setProjectId(claim.getProjectId());
            if(ObjectUtils.isNotEmpty(income)){
                projectIncome.setDch(income.getCwDch());
                projectIncome.setIncomeUnitName(income.getIncomeUnit());
            }
            projectIncome.setIncomeFee( projectIncome.getSchoolFee().add(projectIncome.getOutboundFee()));
            projectIncome.setIncomeDate(claim.getClaimDate());
            claimProjectIncomeMapper.insert(projectIncome);
        }
    }

    /**
     * 删除
     * @param ids
     * @param isValid
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean delCwIncomeclaim(Collection<String> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        //处理状态
        List<String> incomeids = baseMapper.selectIncomdIds(new QueryWrapper<BizCwIncomeClaim>().in("ID",ids).groupBy("CW_INCOME_ID"));
        Boolean flag = baseMapper.deleteBatchIds(ids) >0;
        if (flag){
            budgetMapper.delete(new QueryWrapper<BizClaimFeeCardBudget>().in("CLAIM_ID",ids));
            manageMapper.delete(new QueryWrapper<BizClaimManageFee>().in("CLAIM_ID",ids));
            claimProjectIncomeMapper.delete(new QueryWrapper<BizClaimProjectIncome>().in("CW_INCOME_CLAIM_ID",ids));
        }
        for(String id:incomeids){
            updateIncomeStatus(id);
        }
        return flag;
    }

    /**
     * 获取插入预算费list
     * @param claimAllBo
     * @return
     */
    private List<BizClaimFeeCardBudget>  getBudgetList(BizCwIncomeClaimAllBo claimAllBo){
        List<BizClaimFeeCardBudget> budgetList = new ArrayList<>();
        List<ClaimBudgetFeeShowVo> budgetFeeShowVoList = claimAllBo.getClaimFeeShow().getClaimBudgetFeeShow();
        List<ClaimIncomeFeeVo> incomeFeeVoList = claimAllBo.getClaimFeeShow().getClaimIncomeFeeShow();

        if (budgetFeeShowVoList!=null && !budgetFeeShowVoList.isEmpty()){
            for(ClaimBudgetFeeShowVo budgetFeeShowVo:budgetFeeShowVoList){
                if (budgetFeeShowVo.getClaimSubBudgetFeeShow() !=null && !budgetFeeShowVo.getClaimSubBudgetFeeShow().isEmpty()){
                    for (ClaimSubBudgetFeeShowVo feeShowVo:budgetFeeShowVo.getClaimSubBudgetFeeShow()){
                        if(!budgetFeeShowVo.getSubjectName().equals("合计")){
                            BizClaimFeeCardBudget budget = new BizClaimFeeCardBudget();
                            BeanUtils.copyProperties(budgetFeeShowVo,budget);
                            budget.setClaimId(claimAllBo.getClaimShow().getId());
                            budget.setIncomeId(claimAllBo.getClaimShow().getCwIncomeId());
                            budget.setProjectId(claimAllBo.getClaimShow().getProjectId());
                            budget.setSubjectFee(ObjectUtil.isEmpty(feeShowVo.getBudgetFee())?BigDecimal.ZERO:feeShowVo.getBudgetFee());
                            budget.setFeeChargerId(feeShowVo.getPersonId());
                            budget.setFeeCardNum(ObjectUtils.isNotNull(incomeFeeVoList.get(0))? incomeFeeVoList.get(0).getFeeCardNum() :null);
                            budgetList.add(budget);
                        }
                    }
                }
            }
        }

        //如果纵向项目且为按本次拆分，则要入库一条outboundFee的数据
        if(claimAllBo.getClaimFeeShow().getProjectClass().equals(project_Class_zX) && !claimAllBo.getClaimShow().getBudgetSplitModde().equalsIgnoreCase(budgetSplitModde_lx)){
            BizClaimFeeCardBudget budget = new BizClaimFeeCardBudget();
            budget.setClaimId(claimAllBo.getClaimShow().getId());
            budget.setIncomeId(claimAllBo.getClaimShow().getCwIncomeId());
            budget.setProjectId(claimAllBo.getClaimShow().getProjectId());
            budget.setSubjectFee(claimAllBo.getClaimShow().getOutboundFee());
            budget.setSubjectCode("outboundCode");
            budget.setSubjectId("outboundCode");
            budget.setSubjectName("转拨费");
            budget.setFeeChargerId(ObjectUtils.isNotNull(incomeFeeVoList.get(0))? incomeFeeVoList.get(0).getFeeChargerId() :null);
            budget.setFeeCardNum(ObjectUtils.isNotNull(incomeFeeVoList.get(0))? incomeFeeVoList.get(0).getFeeCardNum() :null);
            budgetList.add(budget);
        }

        return budgetList;
    }

    /**
     * 获取插入管理费list
     * @param claimAllBo
     * @return
     */
    private List<BizClaimManageFee>  getManageList(BizCwIncomeClaimAllBo claimAllBo){
        List<BizClaimManageFee> manageFeeList = new ArrayList<>();
        List<ClaimManageFeeVo> manageFeeVoList = claimAllBo.getClaimFeeShow().getClaimManageFeeShow();
        List<ClaimIncomeFeeVo> incomeFeeVoList = claimAllBo.getClaimFeeShow().getClaimIncomeFeeShow();

        if(manageFeeVoList!=null && !manageFeeVoList.isEmpty()){
            for(ClaimManageFeeVo manageFeeVo:manageFeeVoList) {
                if (manageFeeVo.getClaimSubManageFee() != null && !manageFeeVo.getClaimSubManageFee().isEmpty()) {
                    for (ClaimSubManageFeeVo subManageFeeVo : manageFeeVo.getClaimSubManageFee()) {
                        BizClaimManageFee manageFee = new BizClaimManageFee();
                        manageFee.setSubjectFee(ObjectUtil.isEmpty(subManageFeeVo.getSubjectFee())?BigDecimal.ZERO:subManageFeeVo.getSubjectFee());
                        manageFee.setSplitManageFee(subManageFeeVo.getSplitManageFee());
                        manageFee.setClaimId(claimAllBo.getClaimShow().getId());
                        manageFee.setIncomeId(claimAllBo.getClaimShow().getCwIncomeId());
                        manageFee.setBizType(claimtype);
                        manageFee.setFeeCardNum(ObjectUtils.isNotNull(incomeFeeVoList.get(0)) ? incomeFeeVoList.get(0).getFeeCardNum() : null);
                        manageFee.setFeeChargerId(ObjectUtils.isNotNull(incomeFeeVoList.get(0))?incomeFeeVoList.get(0).getFeeChargerId() : null);
                        manageFee.setProjectId(claimAllBo.getClaimShow().getProjectId());
                        manageFee.setSubjectCode(manageFeeVo.getSubjectCode());
                        manageFee.setSubjectName(manageFeeVo.getSubjectName());
                        manageFeeList.add(manageFee);
                    }
                }
            }
        }
        return manageFeeList;
    }

    @Override
    public void updateBusinessStatus(String tableName, String businessId, String checkStatus, String sysUserId) {
        if (StringUtils.isEmpty(tableName) || StringUtils.isEmpty(businessId) || StringUtils.isEmpty(checkStatus))
            return;
        if ("2".equals(checkStatus)) {
            BizClaimProjectIncome claimProjectIncome = claimProjectIncomeMapper.selectOne(new QueryWrapper<BizClaimProjectIncome>().eq("CW_INCOME_CLAIM_ID",businessId).last(" limit 1"));
            if(ObjectUtils.isNotEmpty(claimProjectIncome)) {
                BizProjectIncome projectIncome = turn(claimProjectIncome);
                //没有卡号，去反写卡号
                if (StringUtils.isEmpty(claimProjectIncome.getFeeCardNum())) {
                    String feecard = sysSnruleService.generateCode("1", projectIncome.getProjectId());
                    projectIncome.setFeeCardNum(feecard);
                    BizClaimProjectIncome income = new BizClaimProjectIncome();
                    income.setFeeCardNum(feecard);
                    claimProjectIncomeMapper.update(income, new UpdateWrapper<BizClaimProjectIncome>().eq("CW_INCOME_CLAIM_ID", businessId));
                    BizClaimFeeCardBudget budget = new BizClaimFeeCardBudget();
                    budget.setFeeCardNum(projectIncome.getFeeCardNum());
                    budgetMapper.update(budget,new UpdateWrapper<BizClaimFeeCardBudget>().eq("CLAIM_ID", businessId));
                    BizClaimManageFee manageFee1 = new BizClaimManageFee();
                    manageFee1.setFeeCardNum(projectIncome.getFeeCardNum());
                    manageMapper.update(manageFee1,new UpdateWrapper<BizClaimManageFee>().eq("CLAIM_ID", businessId));
                }
                proincomeMapper.insert(projectIncome);
                insertFeeCard(projectIncome); //没有卡号要去新增一条数据;
                List<BizClaimFeeCardBudget> budgetList = budgetMapper.selectList(new QueryWrapper<BizClaimFeeCardBudget>().eq("CLAIM_ID", businessId));
                if(budgetList.size()>0){
                    for (BizClaimFeeCardBudget feeCardBudget : budgetList) {
                        BizProjectFeeCardBudget projectFeeCardBudget = new BizProjectFeeCardBudget();
                        BeanUtil.copyProperties(feeCardBudget, projectFeeCardBudget);
                        projectFeeCardBudget.setIncomeId(projectIncome.getId());
                        probudgetMapper.insert(projectFeeCardBudget);
                    }
                }

                List<BizClaimManageFee> manageFeeList = manageMapper.selectList(new QueryWrapper<BizClaimManageFee>().eq("CLAIM_ID", businessId));
                if (manageFeeList.size() >0) {
                    for (BizClaimManageFee claimManageFee : manageFeeList) {
                        BizManageFee manageFee = new BizManageFee();
                        BeanUtil.copyProperties(claimManageFee, manageFee);
                        manageFee.setIncomeId(projectIncome.getId());
                        promanageMapper.insert(manageFee);
                    }
                }
            }
        }
    }

    /**
     * 数据转换
     * @param claimProjectIncome
     * @return
     */
    private BizProjectIncome turn(BizClaimProjectIncome claimProjectIncome){
        SysUser loginUser = SecurityUtils.getLoginUser().getUser();
        BizProjectIncome projectIncome = new BizProjectIncome();
        projectIncome.setCwIncomeId(claimProjectIncome.getCwIncomeId());
        projectIncome.setCwIncomeClaimId(claimProjectIncome.getCwIncomeClaimId());
        projectIncome.setProjectId(claimProjectIncome.getProjectId());
        projectIncome.setFeeCardNum(claimProjectIncome.getFeeCardNum());
        projectIncome.setIncomeFee(claimProjectIncome.getIncomeFee());
        projectIncome.setIncomeDate(claimProjectIncome.getIncomeDate());
        projectIncome.setFeeChargerName(claimProjectIncome.getFeeChargerName());
        projectIncome.setFeeChargerId(claimProjectIncome.getFeeChargerId());
        projectIncome.setUnitId(claimProjectIncome.getUnitId());
        projectIncome.setCheckstatus("2");
        projectIncome.setCheckdate(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        projectIncome.setChecker(loginUser.getNickName());
        projectIncome.setIncomeUnitName(claimProjectIncome.getIncomeUnitName());
        projectIncome.setDch(claimProjectIncome.getDch());
        projectIncome.setIncomeType(claimProjectIncome.getIncomeType());
        projectIncome.setSchoolFee(claimProjectIncome.getSchoolFee());
        projectIncome.setOutboundFee(claimProjectIncome.getOutboundFee());
        projectIncome.setFeeSchemeId(claimProjectIncome.getFeeSchemeId());
        projectIncome.setFeeChargerCode(claimProjectIncome.getFeeChargerCode());
        projectIncome.setFeeChargerUnitName(claimProjectIncome.getFeeChargerUnitName());
        projectIncome.setBizId(claimProjectIncome.getId());
        projectIncome.setBizType(claimtype);
        return projectIncome;
    }

    /**
     * 判断是否要新增卡号
     * @param projectIncome
     */
    private void insertFeeCard(BizProjectIncome projectIncome){
        if(StringUtils.isNotEmpty(projectIncome.getFeeCardNum())){
            Long count = feeCardMapper.selectCount(new QueryWrapper<BizProjectFeeCard>().eq("FEE_CARD_NUM",projectIncome.getFeeCardNum()));
            if(count<=0){
                BizProjectFeeCard feeCard = new BizProjectFeeCard();
                feeCard.setProjectId(projectIncome.getProjectId());
                feeCard.setFeeCardNum(projectIncome.getFeeCardNum());
                feeCard.setFeeChargerCode(projectIncome.getFeeChargerCode());
                feeCard.setFeeChargerId(projectIncome.getFeeChargerId());
                feeCard.setFeeChargerName(projectIncome.getFeeChargerName());
                feeCard.setFeeChargerUnitId(projectIncome.getUnitId());
                feeCard.setTransferState("0");
                feeCardMapper.insert(feeCard);
            }
        }
    }
}
